package com.aurora.oa.signin.view;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.aurora.oa.R;
import com.aurora.oa.activity.BaseActivity;
import com.aurora.oa.customview.InputDialog;
import com.aurora.oa.listener.OnRequestCarHistoryListener;
import com.aurora.oa.listener.OnRequestIsSuccessListener;
import com.aurora.oa.listener.OnRequestTrackHistoryListener;
import com.aurora.oa.model.RequestHttpModel;
import com.aurora.oa.model.RequestHttpModelImpl;
import com.aurora.oa.signin.adapter.TrackHistoryAdapter;
import com.aurora.oa.signin.bean.TrackHistoryBean;
import com.aurora.oa.utils.ToastUtil;
import com.aurora.oa.work.adapter.ApplyCarHistoryAdapter;
import com.aurora.oa.work.bean.ApplyCarHistoryBean;
import com.codbking.calendar.CalendarUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/4/28 0028.
 */
public class TrackHistoryActivity extends BaseActivity{
    RecyclerView recyclerView;
    SwipeRefreshLayout swipeRefreshLayout;
    LinearLayoutManager layoutManager;
    boolean isLoading;
    private int whitchPage =1;
    private List<TrackHistoryBean> data = new ArrayList<>();
    private TrackHistoryAdapter adapter = new TrackHistoryAdapter(this,data, true);
    private Handler handler = new Handler();
    RequestHttpModel requestHttpModel = new RequestHttpModelImpl();
    private String  yearmonth;
    private InputDialog dialog;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initTitlebar(true,"用车申请记录",true);
        setMyContentView(R.layout.activity_refresh_list);
        initView();
        getData();
    }


    //请求数据
    private void getData() {
        String[] date =  CalendarUtil.getYMDZero(new Date());
        yearmonth = date[0]+date[1];
        requestHttpModel.getTrackHistoryData(yearmonth, new OnRequestTrackHistoryListener() {
            @Override
            public void onRequestTrackHistorySuccess(List<TrackHistoryBean> trackHistoryBeanList) {
                refreshList(trackHistoryBeanList);
            }

            @Override
            public void onRequestTrackHistoryFail(String message) {
                ToastUtil.show(getApplicationContext(), message);
                swipeRefreshLayout.setRefreshing(false);
            }

/*            @Override
            public void onRequestCarHistorySuccess(List<TrackHistoryBean> applyCarHistoryBeanList) {
                if(whitchPage==1){
                    doPullDownRefresh(applyCarHistoryBeanList);
                }else{
                    doPullUpLoad(applyCarHistoryBeanList);
                }
            }

            @Override
            public void onRequestCarHistoryFail(String message) {
                ToastUtil.show(getApplicationContext(),message);
                swipeRefreshLayout.setRefreshing(false);
            }
        });*/
        });
    }

    private void refreshList(List<TrackHistoryBean> trackHistoryBeanList) {
        data.clear();
        data.addAll(trackHistoryBeanList);
        adapter.notifyDataSetChanged();
        swipeRefreshLayout.setRefreshing(false);
    }

    private void initView() {

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.SwipeRefreshLayout);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        swipeRefreshLayout.setColorSchemeResources(R.color.blue,R.color.white);
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
            }
        });

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        whitchPage = 1;
                        data.clear();
                        getData();
                    }
                }, 0);
            }
        });
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new TrackHistoryAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, final int position) {
                //修改备注
                final InputDialog.Builder contactsBuilder = new
                        InputDialog.Builder(TrackHistoryActivity.this);
                contactsBuilder.setTitle("修改备注")
                        .setNegativeButton("取消",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        requestHttpModel.doSignComment(data.get(position).id,contactsBuilder.getInput(), new OnRequestIsSuccessListener() {
                                            @Override
                                            public void onRequestSuccess(String info) {
                                                ToastUtil.show(getApplicationContext(),info);

                                            }

                                            @Override
                                            public void onRequestFail(String message) {
                                                ToastUtil.show(getApplicationContext(),message);
                                            }
                                        });
                                       // myCenterFragmentPresenter.creatContacts(contactsBuilder.getInput());
                                    }
                                });
                dialog = contactsBuilder.create();
                dialog.show();
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }

        });
/*        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.d("test", "StateChanged = " + newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("test", "onScrolled");
                loadMoreData();
            }
        });*/

    }

    //根据位置自动判断是否加载更多数据
    private void loadMoreData(){
        int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
        if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
            Log.d("test", "loading executed");
            boolean isRefreshing = swipeRefreshLayout.isRefreshing();
            if (isRefreshing) {
                adapter.notifyItemRemoved(adapter.getItemCount());
                return;
            }
            if (!isLoading) {
                isLoading = true;
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        whitchPage +=1;
                        getData();
                        Log.d("test", "load more completed");
                        //     isLoading = false;
                    }
                }, 0);
            }
        }
    }

    public void doPullDownRefresh(List<TrackHistoryBean> dataList) {
        data.addAll(dataList);
        adapter.notifyDataSetChanged();
        adapter.setHasMoreData(true);
        swipeRefreshLayout.setRefreshing(false);
        adapter.notifyItemRemoved(adapter.getItemCount());
        //防止页数太少不加载了，滑动的时候会自动判断，判断静止的时候就自己去加载了，0表示不滑动了
        if(recyclerView.getScrollState()==0){
            loadMoreData();
        }
    }


    public void doPullUpLoad(List<TrackHistoryBean> dataList) {
        isLoading = false;
        swipeRefreshLayout.setRefreshing(false);
        if(dataList==null||dataList.size()==0){
            adapter.setHasMoreData(false);
        }else{
            data.addAll(dataList);
        }
        adapter.notifyDataSetChanged();
        adapter.notifyItemRemoved(adapter.getItemCount());
    }

}
